package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityDevicePublishBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.jicai.entity.FilterEntity;
import com.sgb.kjwl.model.entity.lease.PriceSetEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.sgb.kjwl.view.ui.activity.house.LeasePriceSetActivity;
import com.sgb.kjwl.view.ui.adapter.lease.PriceShowAdapter;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.link.entity.PublicTypeEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddDeviceEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.PublicAttrEntity;
import com.sgb.link.entity.ReturnTypeEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.view.event.PickEvent;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.TimeRangePopWindow4;
import com.sgb.kjwl.view.widget.house.MachineAttrView;
import com.sgb.kjwl.viewmodel.self.publish.DevicePublishModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MDateUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_DEVICE_ATTR;
import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_DEVICE_RETURN;

/**
 * 设备出租发布
 */
public class DevicePublishActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    @Inject
    DevicePublishModel viewModel;

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ActivityDevicePublishBinding binding;
    private List<PickSelectEntity> serviceEntities;
    //图片上传
    private List<LocalMedia> selectList = new ArrayList<>();
    private ImageAdapter adapter;
    private final List<String> urls = new ArrayList<>();
    private final List<File> fileList = new ArrayList<>();
    public int imgTotal;
    private int currentImgNum;
    private final List<String> uploadImgList = new ArrayList<>();

    private List<PublicTypeEntity<List<PublicTypeEntity>>> publicTypeEntityList;
    private List<FilterEntity<List<FilterEntity>>> attrList = new ArrayList<>();
    private List<UnitEntity> unitEntityList;
    private AddDeviceEntity addDeviceEntity = new AddDeviceEntity();
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private PriceShowAdapter priceShowAdapter;
    private boolean isLoaded = false;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private int unitPosition;
    private ReturnTypeEntity returnTypeEntity;
    //    private boolean isUpdate = false;
    private Intent intent;
    private Bundle bundle;
    private String titleString;
    //    private Gson gson;
    private List<PickSelectEntity> driverDatas, invoiceDatas, invoiceGGDatas, transportData, priceFixdData;
    private List<PickSelectEntity> tariffDatas = new ArrayList<>();
    private List<PickSelectEntity> departmentData = new ArrayList<>();
    private String updateUserNo = "";
    private boolean isApprove = false;//是否需要审批
    private String myCompanyNo;
    private String id;
    private List<PublicAttrEntity> mEditAttrlist;
    //private String mEditPriceUnit;

    private List<PickSelectEntity<List<PickSelectEntity>>> timeUnitList;
    private List<PriceSetEntity> priceSetList = new ArrayList<>();//价格设置参数列表

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, DevicePublishActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.setClass(context, DevicePublishActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }

    /**
     *
     */
    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(DevicePublishActivity.this, R.layout.activity_device_publish);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("设备出租发布");
        binding.topLayout.ivBack.setOnClickListener(v -> onBackPressed());
        binding.include.tvUse.setOnClickListener(this);
        binding.btnSave.setOnClickListener(this);
        binding.btnSubmit.setOnClickListener(this);
        binding.include.tvUse.setOnClickListener(this);
        binding.itemTvType.setOnWholeItemClickListener(this);
        binding.itemMap.setOnWholeItemClickListener(this);
        //binding.itemTvUnit.setOnClickListener(this);
        binding.itemTvRange.setOnWholeItemClickListener(this);
        binding.itemTvAttribute.setOnWholeItemClickListener(this);
        binding.itemTvDriver.setOnWholeItemClickListener(this);
        //binding.itemTvUnit.setOnClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvInvoiceGg.setOnWholeItemClickListener(this);
        binding.itemTvServicer.setOnWholeItemClickListener(this);
        binding.itemTvAllowTime.setOnWholeItemClickListener(this);
//        binding.itemTvPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
//        binding.itemTvPrice.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 2)});
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvSl.setOnWholeItemClickListener(this);
        binding.itemTvDepartmentName.setOnWholeItemClickListener(this);
        binding.itemTvTransport.setOnWholeItemClickListener(this);
        binding.itemTvPriceIsFixed.setOnWholeItemClickListener(this);
        binding.itemTvPriceSet.setOnWholeItemClickListener(this);
        binding.tvNum.setFilters(new EditInputFilter[]{new EditInputFilter(9999, 1, 0)});
        binding.tvAdd.setOnClickListener(v -> add());
        binding.tvSub.setOnClickListener(v -> sub());

        adapter = new ImageAdapter(this, null, null, 5);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(DevicePublishActivity.this, 4));
        binding.recyclerView.setAdapter(adapter);
        //binding.nS.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //ns获取焦点 会导致屏幕变暗
//        binding.nS.setFocusable(true);
//        binding.nS.setFocusableInTouchMode(true);
//        binding.nS.setOnTouchListener((v, event) -> {
//            v.requestFocusFromTouch();
//            return false;
//        });
        setListener();
        initPriceAdapter();
    }


    //设置监听事件
    private void setListener() {
        binding.itemTvModel.onTextChange(s -> {
            setDefaultTitle();
        });

        binding.itemTvBrand.onTextChange(s -> {
            setDefaultTitle();
        });

//        binding.cb.setOnCheckedChangeListener((compoundButton, b) -> {
//            if (b) {
//                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setNegotiable("1");
//                binding.itemTvPrice.setVisibility(View.GONE);
//                binding.itemTvUnit.setVisibility(View.GONE);
//                binding.ivUnit.setVisibility(View.GONE);
//                binding.cb.setText("您已选择面议，再次点击退出面议");
//                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setRentalPrice("0");
//            } else {
//                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setNegotiable("0");
//                binding.itemTvPrice.setVisibility(View.VISIBLE);
//                binding.itemTvUnit.setVisibility(View.VISIBLE);
//                binding.ivUnit.setVisibility(View.VISIBLE);
//                binding.cb.setText("面议");
//            }
//        });
    }

    private void setDefaultTitle() {
        if (TextUtils.isEmpty(binding.itemTvType.getContent()) ||
                (!TextUtils.isEmpty(binding.itemTvType.getContent()) && !binding.itemTvType.getContent().contains("-"))) {
            titleString = "出租" + binding.itemTvBrand.getContent() + binding.itemTvModel.getContent();
        } else {
            titleString = "出租" + binding.itemTvBrand.getContent()
                    + binding.itemTvModel.getContent()
                    + binding.itemTvType.getContent().substring(binding.itemTvType.getContent().indexOf("-") + 1);
            ;
        }

        titleString = titleString.replace("//", " ");
//        if (titleString.indexOf("/") == titleString.length() - 1) {
//            titleString = titleString.substring(0, titleString.length() - 1);
//        }
        binding.include.tvTitleDefault.setText(titleString);
        binding.include.rlLeaseTitle.setVisibility(View.VISIBLE);
    }

    private void initPriceAdapter() {
        priceShowAdapter = new PriceShowAdapter(this, null);
        binding.rvPrice.setLayoutManager(new LinearLayoutManager(this));
        binding.rvPrice.setAdapter(priceShowAdapter);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void init() {
        driverDatas = new ArrayList<>();
        //是否带操作员（0:是;1:否）
        driverDatas.add(new PickSelectEntity("1", "是"));
        driverDatas.add(new PickSelectEntity("0", "否"));

        //是否选择发票（0:是;1:否）
        invoiceDatas = new ArrayList<>();
        invoiceDatas.add(new PickSelectEntity("1", "是"));
        invoiceDatas.add(new PickSelectEntity("0", "否"));
        //发票类型
        invoiceGGDatas = new ArrayList<>();
        invoiceGGDatas.add(new PickSelectEntity("0", "普通发票"));
        invoiceGGDatas.add(new PickSelectEntity("1", "专用发票"));

        //是否提供运输
        transportData = new ArrayList<>();
        transportData.add(new PickSelectEntity("1", "提供(运输费用协商解决)"));
        transportData.add(new PickSelectEntity("2", "不提供"));

        //租赁价格类型
        priceFixdData = new ArrayList<>();
        priceFixdData.add(new PickSelectEntity("0", "一口价"));
        priceFixdData.add(new PickSelectEntity("1", "面议"));

        initDefault();
        if (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra("id"))) {
            id = getIntent().getStringExtra("id");
            viewModel.getDetailModel(id);
            binding.topLayout.titleView.setText("设备出租编辑");
        }
    }

    //设置默认参数
    private void initDefault() {
        binding.itemTvPriceIsFixed.setContent("一口价");
        binding.itemTvDriver.setContent("否");
        binding.itemTvInvoice.setContent("是");
        binding.itemTvInvoiceGg.setContent("普通发票");
        binding.itemTvTransport.setContent("提供(运输费用协商解决)");
        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setHasOperator("0");
        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setNeedInvoice("1");
        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setInvoiceType("0");
        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setSupportTransport("1");
//        viewModel.getPriceUnitModel(1);
        viewModel.getLeaseTimeUnit("1");
        viewModel.getLeaseRate();
        updateUserNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        myCompanyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String myCompanyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String contact = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String loginPhone = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, "");
        binding.itemTvDepartmentUnit.setContent(myCompanyName);
        binding.itemTvDepartmentPerson.setContent(contact);

        binding.itemTvPerson.setContent(contact);
        binding.itemTvPhone.setContent(loginPhone);

        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setContactName(contact);
        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setContactPhone(loginPhone);

        //企业用户获取申请 部门
        if (!TextUtils.isEmpty(myCompanyNo) && !"0".equals(myCompanyNo)) {
            viewModel.getDepartment();
            binding.itemTvDepartmentUnit.setVisibility(View.VISIBLE);
            binding.itemTvDepartmentName.setVisibility(View.VISIBLE);
            binding.itemTvDepartmentPerson.setVisibility(View.VISIBLE);
        }
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        }
    }

    //图片上传成功回调
    public void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            urlList.add(urls.get(i));
        }

        if (type == 0) {
            if (addDeviceEntity.getPictures() != null) {
                addDeviceEntity.getPictures().addAll(urlList);
                urlList.clear();
                urlList.addAll(addDeviceEntity.getPictures());
            }
        }
        StringBuilder stringBuilder = new StringBuilder("");
        for (int i = 0; i < urlList.size(); i++) {
            if (i == urlList.size() - 1) {
                stringBuilder.append(urlList.get(i));
            } else {
                stringBuilder.append(urlList.get(i)).append(",");
            }
        }
        String urlStrs = stringBuilder.toString();
        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setImgPath(urlStrs);

        //企业用户判断是否需要审批
        if (binding.itemTvDepartmentName.getVisibility() == View.VISIBLE && !"0".equals(viewModel.addDeviceEntity.get().getStatus())) {
            viewModel.haveApprovalOrNot(myCompanyNo, "facilityRelease");
        } else {
//            if (isUpdate) {
//                viewModel.addDeviceModel();
//            } else {
            viewModel.addDeviceModel();
            binding.btnSubmit.setClickable(false);
//            }
        }
    }

    public void showEditView(AddDeviceEntity addDeviceEntity) {
        if (addDeviceEntity == null) {
            return;
        }
//        this.isUpdate = true;
        this.addDeviceEntity = addDeviceEntity;
        viewModel.addDeviceEntity.set(addDeviceEntity);

        if (!TextUtils.isEmpty(addDeviceEntity.getDepartmentName()) && updateUserNo.equals(addDeviceEntity.getUpdateUserNo())) {
            binding.itemTvDepartmentName.setContent(addDeviceEntity.getDepartmentName());
        } else {
            viewModel.addDeviceEntity.get().setDepartmentNo("");
            viewModel.addDeviceEntity.get().setDepartmentName("");
        }

//        if ("1".equals(addDeviceEntity.getNegotiable())) {
//            binding.cb.setChecked(true);
//            binding.cb.setText("您已选择面议，再次点击退出面议");
//            binding.itemTvPrice.setVisibility(View.GONE);
//            binding.itemTvUnit.setVisibility(View.GONE);
//            binding.ivUnit.setVisibility(View.GONE);
//        } else {
//            binding.cb.setChecked(false);
//            binding.cb.setText("面议");
//            binding.itemTvPrice.setVisibility(View.VISIBLE);
//            binding.itemTvUnit.setVisibility(View.VISIBLE);
//            binding.ivUnit.setVisibility(View.VISIBLE);
//            binding.itemTvPrice.setText(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getRentalPrice());
//            mEditPriceUnit = Objects.requireNonNull(viewModel.addDeviceEntity.get()).getPriceUnitName();
//            binding.itemTvUnit.setText(mEditPriceUnit);
//        }

//        if ("0".equals(addDeviceEntity.getNegotiable())) {
//            binding.cb.setChecked(false);
//            binding.itemTvPrice.setText(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getRentalPrice());
//            mEditPriceUnit = Objects.requireNonNull(viewModel.addDeviceEntity.get()).getPriceUnitName();
//            binding.itemTvUnit.setText(mEditPriceUnit);
//        } else {
//            binding.cb.setChecked(true);
//        }

        if ("1".equals(addDeviceEntity.getHasOperator())) {
            binding.itemTvDriver.setContent("是");
        } else {
            binding.itemTvDriver.setContent("否");
        }
        if ("1".equals(addDeviceEntity.getNeedInvoice())) {
            binding.itemTvInvoice.setContent("是");
            binding.itemTvSl.setVisibility(View.VISIBLE);
            binding.itemTvSl.setContent(addDeviceEntity.getTariff() + "%");
            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
            if ("0".equals(addDeviceEntity.getInvoiceType())) {
                binding.itemTvInvoiceGg.setContent("普通发票");
            } else {
                binding.itemTvInvoiceGg.setContent("专用发票");
            }
        } else {
            binding.itemTvInvoice.setContent("否");
            binding.itemTvInvoiceGg.setVisibility(View.GONE);
            binding.itemTvSl.setVisibility(View.GONE);
        }

        binding.itemTvServicer.setContent(addDeviceEntity.getCustomerServiceName());

        if (!TextUtils.isEmpty(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getWorkStartTime())) {
            binding.itemTvAllowTime.setContent(MDateUtil.getByTimestamp(Long.parseLong(addDeviceEntity.getWorkStartTime()), MDateUtil.Format.FORMART6.name) + "-" + MDateUtil.getByTimestamp(Long.parseLong(addDeviceEntity.getWorkEndTime()), MDateUtil.Format.FORMART6.name));
        } else {
            binding.itemTvAllowTime.setContent("");
        }

        if (!TextUtils.isEmpty(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getFirstCategoryName())) {
            binding.itemTvType.setContent(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getFirstCategoryName()
                    + "-" + Objects.requireNonNull(viewModel.addDeviceEntity.get()).getSecondCategoryName());
        }

        //binding.itemTvUnit.setText(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getPriceUnitName());

        if (!TextUtils.isEmpty(addDeviceEntity.getLocation().getProvinceName())) {
            binding.itemTvRange.setContent(addDeviceEntity.getLocation().getProvinceName()
                    + addDeviceEntity.getLocation().getCityName()
                    + addDeviceEntity.getLocation().getAreaName());
        }

        if (addDeviceEntity.getAttributeList() != null && addDeviceEntity.getAttributeList().size() > 0) {
            //binding.itemTvAttribute.setContent(Objects.requireNonNull(addDeviceEntity.getDeviceAttrEntityList().get(0)).getName());
            //binding.itemTvAttribute.setContent("已选择");
            mEditAttrlist = addDeviceEntity.getAttributeList();
            initDevicePublistAttrData();
        }

        if (!TextUtils.isEmpty(addDeviceEntity.getLocation().getAddress())) {
            binding.etDetailAddress.setText(addDeviceEntity.getLocation().getAddress());
        }

//        //图片
//        if (Objects.requireNonNull(viewModel.addDeviceEntity.get()).getPictures().size() > 0) {
//            adapter.setNetImgList(viewModel.addDeviceEntity.get().getPictures());
//        }

        //图片
        if (!TextUtils.isEmpty(addDeviceEntity.getImgPath())) {
            String imgPath = addDeviceEntity.getImgPath();
            List<String> imgs = new ArrayList<>();
            if (imgPath.contains(",")) {
                String[] img = imgPath.split(",");
                if (img != null && img.length > 1) {
                    for (String url : img) {
                        imgs.add(url);
                    }
                }
            } else {
                imgs.add(imgPath);
            }
            adapter.setNetImgList(imgs);
        }

        binding.include.itemTvTitleEdit.setEditContent(addDeviceEntity.getTitle());
        //闲置数量
        binding.tvNum.setText(viewModel.addDeviceEntity.get().getAsideNum());
        //是否提供运输
        if ("1".equals(viewModel.addDeviceEntity.get().getSupportTransport())) {
            binding.itemTvTransport.setContent("提供(运输费用协商解决)");
        } else {
            binding.itemTvTransport.setContent("不提供");
        }

        //租赁价格类型
        if ("0".equals(viewModel.addDeviceEntity.get().getNegotiable())) {
            binding.itemTvPriceIsFixed.setContent("一口价");
            binding.itemTvPriceSet.setVisibility(View.VISIBLE);
        } else {
            binding.itemTvPriceIsFixed.setContent("面议");
            binding.itemTvPriceSet.setVisibility(View.GONE);
        }

        //价格设置
        priceSetList = addDeviceEntity.getPriceList();
        checkReatePrice();
        //设置默认推荐标题
        setDefaultTitle();
    }


    //选择设备类型
    public void showDeviceType(List<PublicTypeEntity<List<PublicTypeEntity>>> publicTypeEntityList) {
        this.publicTypeEntityList = publicTypeEntityList;
        if (intent == null) {
            intent = new Intent();
            bundle = new Bundle();
        }
        bundle.putSerializable("publicTypeEntityList", (Serializable) publicTypeEntityList);
        bundle.putInt("type", EVENT_PUBLISH_DEVICE_RETURN);
        intent.putExtras(bundle);
        PublicPublishTypeActivity.start(this, intent);
    }

    //注册地址
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                viewModel.addDeviceEntity.get().getLocation().setAreaName(areaName);
                viewModel.addDeviceEntity.get().getLocation().setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.itemTvRange.setContent(content);
            binding.etDetailAddress.setText("");
            binding.etDetailAddress.setHint("请输入详细地址");

            cityPosition1 = options1;
            cityPosition2 = options2;
            viewModel.addDeviceEntity.get().getLocation().setProvinceName(addressEntityList.get(options1).getName());
            viewModel.addDeviceEntity.get().getLocation().setProvinceNo(addressEntityList.get(options1).getId());
            viewModel.addDeviceEntity.get().getLocation().setCityName(opt2.get(options1).get(options2).getName());
            viewModel.addDeviceEntity.get().getLocation().setCityNo(opt2.get(options1).get(options2).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

//    @SuppressWarnings("unchecked")
//    private void showUnitPop() {
//        OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
//            String content = unitEntityList.get(options1).getName();
//            binding.itemTvUnit.setText(content);
//            unitPosition = options1;
//            Objects.requireNonNull(viewModel.addDeviceEntity.get()).setPriceUnitNo(unitEntityList.get(options1).getNo());
//            Objects.requireNonNull(viewModel.addDeviceEntity.get()).setPriceUnitName(unitEntityList.get(options1).getName());
//        }).build();
//        businessOption.setPicker(unitEntityList);
//        businessOption.setSelectOptions(unitPosition);
//        businessOption.show();
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                initDialog();
                break;
//            case R.id.item_tv_unit:
//
//                hideKeyboard();
//
//                if (unitEntityList != null) {
//                    showUnitPop();
//                } else {
//                    viewModel.getPriceUnitModel(2);
//                }
//                break;
            case R.id.btn_save:
                viewModel.addDeviceEntity.get().setStatus("0");
                validate();
                break;
            case R.id.btn_submit:
                viewModel.addDeviceEntity.get().setStatus("1");
                validate();
                break;
            case R.id.tv_use:
                binding.include.itemTvTitleEdit.setEditContent(binding.include.tvTitleDefault.getText().toString());
                break;
        }
    }

    private void validate() {
        if (TextUtils.isEmpty(binding.itemTvType.getContent())) {
            MToast.showToast(DevicePublishActivity.this, "请选择设备类型");
            return;
//        } else if (TextUtils.isEmpty(binding.itemTvUnit.getText()) && !binding.cb.isChecked()) {
//            MToast.showToast(DevicePublishActivity.this, "请选择价格单位");
//            return;
//        } else if (TextUtils.isEmpty(binding.itemTvPrice.getText()) && !binding.cb.isChecked()) {
//            MToast.showToast(DevicePublishActivity.this, "请选择租赁价格");
//            return;
//        } else if (!TextUtils.isEmpty(binding.itemTvPrice.getText()) && !binding.cb.isChecked() && Double.parseDouble(binding.itemTvPrice.getText().toString()) <= 0) {
//            MToast.showToast(DevicePublishActivity.this, "请输入大于0的价格");
//            return;
        } else if (adapter.getUrls().size() == 0) {
            MToast.showToast(DevicePublishActivity.this, "请选择图片");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvPerson.getContent())) {
            MToast.showToast(DevicePublishActivity.this, "请填写联系人姓名");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            MToast.showToast(DevicePublishActivity.this, "请填写联系电话");
            return;
        } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent())) {
            MToast.showToast(DevicePublishActivity.this, "请填写正确的电话号码");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvRange.getContent())) {
            MToast.showToast(DevicePublishActivity.this, "请选择所在地区");
            return;
        } else if (TextUtils.isEmpty(binding.etDetailAddress.getText())) {
            MToast.showToast(DevicePublishActivity.this, "请选择详细地址");
            return;
        } else if (TextUtils.isEmpty(binding.itemTvScope.getContent())) {
            MToast.showToast(DevicePublishActivity.this, "请输入服务地区");
            return;
        }

        if (binding.itemTvInvoice.getContent().equals("是")) {
            if (TextUtils.isEmpty(binding.itemTvSl.getContent())) {
                Toast.makeText(this, "请选择税率", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        //兼容服务端,否则服务端会报错
        if (TextUtils.isEmpty(viewModel.addDeviceEntity.get().getDepartmentNo())) {
            Objects.requireNonNull(viewModel.addDeviceEntity.get()).setDepartmentNo("");
        }

        if (TextUtils.isEmpty(binding.tvNum.getText())) {
            MToast.showToast(this, "请输入闲置数量");
            return;
        }

        //非面议时,价格设置必填
        if ("0".equals(viewModel.addDeviceEntity.get().getNegotiable()) && priceSetList.size() == 0) {
            MToast.showToast(this, "请设置租赁价格");
            return;
        }

        //面议时设置价格为
        if ("1".equals(viewModel.addDeviceEntity.get().getNegotiable())) {
            viewModel.addDeviceEntity.get().setRentalPrice("");
            viewModel.addDeviceEntity.get().setPriceList(new ArrayList<>());
        }
        //闲置数量
        viewModel.addDeviceEntity.get().setAsideNum(binding.tvNum.getText().toString());
        //服务区域
        viewModel.addDeviceEntity.get().setServiceArea(binding.itemTvScope.getContent());

        String title = binding.include.itemTvTitleEdit.getEditContent().trim();
        if (TextUtils.isEmpty(title)) {//如果自定义标题为空,则上传默认标题
//            viewModel.addDeviceEntity.get().setTitle(binding.include.tvTitleDefault.getText().toString());
            MToast.showToast(this, "请输入租赁名称");
            return;
        } else {
            viewModel.addDeviceEntity.get().setTitle(title);
        }

        if (!checkChooseAttr()) {//检测是否有必填属性为空
            return;
        } else {
            viewModel.addDeviceEntity.get().setAttributeList(binding.mAttrView.getChooseAttr());
        }

        if (adapter.getFileList().size() != 0) {
            currentImgNum = 0;
            uploadImgList.clear();
            imgTotal = adapter.getFileList().size();
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        } else {
            uploadImgSuccess(adapter.getUrls(), 1);
        }
    }

    public boolean checkChooseAttr() {
        List<PublicAttrEntity> chooseAttr = binding.mAttrView.getChooseAttr();
        if (chooseAttr == null || chooseAttr.size() <= 0) {
            return true;
        }
        for (int i = 0; i < chooseAttr.size(); i++) {
            if (chooseAttr.get(i) != null) {
                if ("1".equals(chooseAttr.get(i).getKey()) && TextUtils.isEmpty(chooseAttr.get(i).getAttributeVal())) {
                    MToast.showToast(this, "请选择或填写属性值");
                    return false;
                }
            }

        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 图片、视频、音频选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }

        if (requestCode == 255) {
            if (data == null) {
                return;
            }
            double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            binding.etDetailAddress.setText(address + "");
            viewModel.addDeviceEntity.get().getLocation().setLatitude(lat + "");
            viewModel.addDeviceEntity.get().getLocation().setLongitude(lon + "");
            viewModel.addDeviceEntity.get().getLocation().setAddress(address);
        }
        if (requestCode == 260 && data != null) {
            priceSetList = (List<PriceSetEntity>) data.getSerializableExtra("priceSetList");
            checkReatePrice();
            viewModel.addDeviceEntity.get().setPriceList(priceSetList);
        }
    }

    //计算所有选项的含税价
    private void checkReatePrice() {
        if (priceSetList == null || priceSetList.size() == 0) return;
        binding.itemTvPriceSet.setContent("已设置");
        for (PriceSetEntity entity : priceSetList) {
            entity.setDriverReatePrice(getRatePrice(entity.getDriverPrice()));
            entity.setNoDriverReatePrice(getRatePrice(entity.getNoDriverPrice()));
            entity.setRentNo(viewModel.addDeviceEntity.get().getNo());
            if (binding.itemTvSl.getVisibility() == View.GONE) {//若为不提供发票，则清除所有含税价
                entity.setDriverReatePrice("");
                entity.setNoDriverReatePrice("");
            }
        }
        setRatePriceText();
    }


    //计算含税价
    private String getRatePrice(String price) {
        try {
            if (TextUtils.isEmpty(viewModel.addDeviceEntity.get().getTariff())) {
                return new DecimalFormat("0.00").format(Double.parseDouble(price));
            } else {
                Double tariff = Double.parseDouble(viewModel.addDeviceEntity.get().getTariff());
                Double ratePrice = Double.parseDouble(price) + Double.parseDouble(price) * tariff / 100;
                return new DecimalFormat("0.00").format(ratePrice);
            }
        } catch (Exception ex) {
            return price;
        }
    }

    private void setRatePriceText() {
        if (priceSetList != null && "0".equals(viewModel.addDeviceEntity.get().getNegotiable())) {
            boolean isDriver = "1".equals(viewModel.addDeviceEntity.get().getHasOperator());
            boolean isDTariff = "1".equals(viewModel.addDeviceEntity.get().getNeedInvoice());//有发票
            priceShowAdapter.setDriverAndTariff(isDriver, isDTariff);
            priceShowAdapter.setCategoryType("1");//设备类型
            priceShowAdapter.setDatas(priceSetList);
        }
    }

    //加
    private void add() {
        if (TextUtils.isEmpty(binding.tvNum.getText().toString().trim())) {
            return;
        }
        int num = Integer.parseInt(binding.tvNum.getText().toString());
        if (num == 9999) {//最大 9999
            return;
        }
        num += 1;
        binding.tvNum.setText(num + "");
    }

    //减
    private void sub() {
        int num = Integer.parseInt(binding.tvNum.getText().toString());
        if (num <= 1) {
            num = 1;
        } else {
            num -= 1;
        }
        binding.tvNum.setText(num + "");
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_driver://选择是否自带操作员
                if (null != driverDatas && driverDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
                        String content = driverDatas.get(options1).getProjectscale();
                        binding.itemTvDriver.setContent(content);
                        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setHasOperator(driverDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(driverDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice://选择是否开具发票
                if (null != invoiceDatas && invoiceDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
                        String content = invoiceDatas.get(options1).getProjectscale();
                        binding.itemTvInvoice.setContent(content);
                        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setNeedInvoice(invoiceDatas.get(options1).getNo());
                        if ("否".equals(content)) {
                            binding.itemTvInvoiceGg.setVisibility(View.GONE);
                            binding.itemTvSl.setVisibility(View.GONE);
                        } else {
                            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
                            binding.itemTvSl.setVisibility(View.VISIBLE);
                        }
                        checkReatePrice();
                    }).build();
                    businessOption.setPicker(invoiceDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice_gg://选择发票类型
                if (null != invoiceGGDatas && invoiceGGDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
                        String content = invoiceGGDatas.get(options1).getProjectscale();
                        binding.itemTvInvoiceGg.setContent(content);
                        Objects.requireNonNull(viewModel.addDeviceEntity.get()).setInvoiceType(invoiceGGDatas.get(options1).getNo());
                        checkReatePrice();
                    }).build();
                    businessOption.setPicker(invoiceGGDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_sl://税率
                if (null != tariffDatas && tariffDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
                        binding.itemTvSl.setContent(tariffDatas.get(options1).getProjectscale());
                        viewModel.addDeviceEntity.get().setTariff(tariffDatas.get(options1).getNo());
                        checkReatePrice();//重新根据税率计算含税价
                    }).build();
                    businessOption.setPicker(tariffDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_allow_time://选择时间
                TimeRangePopWindow4 timeRangePopWindow4 = new TimeRangePopWindow4(getActivity());
                timeRangePopWindow4.setOnTimeCallBack(new TimeRangePopWindow4.OnTimeCallBack() {

                    @Override
                    public void result(long startTime, long endTime, String content) {
                        if (startTime < endTime) {
                            binding.itemTvAllowTime.setContent(content);
                            viewModel.addDeviceEntity.get().setWorkStartTime(String.valueOf(startTime));
                            viewModel.addDeviceEntity.get().setWorkEndTime(String.valueOf(endTime));
                            timeRangePopWindow4.dismiss();
                        } else {
                            MToast.showToast(DevicePublishActivity.this, "结束时间不能小于开始时间");
                        }
                    }
                });
                timeRangePopWindow4.showAtLocation(binding.mainLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.item_tv_servicer://选择客服人员
                if (this.serviceEntities == null) {
                    viewModel.getCustomerOrgDatas();
                } else {
                    if (null != serviceEntities && serviceEntities.size() > 0) {
                        OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
                            String content = serviceEntities.get(options1).getProjectscale();
                            binding.itemTvServicer.setContent(content);
                            Objects.requireNonNull(viewModel.addDeviceEntity.get()).setCustomerServiceId(serviceEntities.get(options1).getNo());
                        }).build();
                        businessOption.setPicker(serviceEntities);
                        businessOption.setSelectOptions(0);
                        businessOption.show();
                    }
                }
                break;
            case R.id.item_tv_type://选择设备类型
                if (publicTypeEntityList != null) {
                    Intent intentType = new Intent();
                    Bundle bundleType = new Bundle();
                    bundleType.putSerializable("publicTypeEntityList", (Serializable) publicTypeEntityList);
                    bundleType.putInt("type", EVENT_PUBLISH_DEVICE_RETURN);
                    intentType.putExtras(bundleType);
                    PublicPublishTypeActivity.start(this, intentType);
                } else {
                    viewModel.getParentDeviceType();
                }
                break;
            case R.id.item_tv_range://选择所在地区
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
//            case R.id.item_tv_attribute://选择设备属性
//                if (attrList != null) {
//                    setAttr(attrList);
//                } else {
//                    if (returnTypeEntity != null) {
//                        viewModel.getDeviceAttr(returnTypeEntity.getFirstNo(), returnTypeEntity.getSecondNo());
//                    } else if (addDeviceEntity != null && !TextUtils.isEmpty(addDeviceEntity.getFirstCategory()) && !TextUtils.isEmpty(addDeviceEntity.getSecondCategory())) {
//                        viewModel.getDeviceAttr(addDeviceEntity.getFirstCategory(), addDeviceEntity.getSecondCategory());
//                    } else {
//                        MToast.showToast(DevicePublishActivity.this, "请选先选择机械类型");
//                    }
//                }
//                break;
            case R.id.item_tv_transport://是否提供运输
                if (null != transportData && transportData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = transportData.get(options1).getProjectscale();
                                binding.itemTvTransport.setContent(content);
                                Objects.requireNonNull(viewModel.addDeviceEntity.get()).
                                        setSupportTransport(transportData.get(options1).getNo());

                            }).build();
                    businessOption.setPicker(transportData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_price_is_fixed://租赁价格类型
                if (null != priceFixdData && priceFixdData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = priceFixdData.get(options1).getProjectscale();

                                if ("面议".equals(content)) {
                                    //判断是否有会员价
                                    if (viewModel.addDeviceEntity.get().getMaxPrices() != null && viewModel.addDeviceEntity.get().getMaxPrices().size() > 0) {
                                        MToast.showToast(DevicePublishActivity.this, "已设置会员价的租赁商品不能再修改为面议");
                                        return;
                                    }
                                }

                                binding.itemTvPriceIsFixed.setContent(content);
                                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setNegotiable(priceFixdData.get(options1).getNo());
                                if ("1".equals(viewModel.addDeviceEntity.get().getNegotiable())) {
                                    binding.itemTvPriceSet.setVisibility(View.GONE);
                                    binding.rvPrice.setVisibility(View.GONE);
                                } else {
                                    binding.itemTvPriceSet.setVisibility(View.VISIBLE);
                                    binding.rvPrice.setVisibility(View.VISIBLE);
                                    setRatePriceText();
                                }
                            }).build();
                    businessOption.setPicker(priceFixdData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_price_set://价格设置
                if (timeUnitList == null || timeUnitList.size() == 0) {
                    MToast.showToast(DevicePublishActivity.this, "租赁单位获取失败");
                    return;
                }
                try {
                    Intent intent = new Intent();
                    //intent.putExtra("maxPrice",maxPrice);//最高会员价
                    intent.putExtra("timeUnitList", (Serializable) timeUnitList);
                    intent.putExtra("priceSetList", (Serializable) priceSetList);
                    intent.putExtra("categoryType", "1");//设备
                    intent.putExtra("isDriver", false);
                    //intent.putExtra("isDriver", "1".equals(Objects.requireNonNull(viewModel.addDeviceEntity.get()).getHasOperator()));
                    intent.setClass(DevicePublishActivity.this, LeasePriceSetActivity.class);
                    startActivityForResult(intent, 260);
                } catch (Exception e) {
                    MToast.showToast(DevicePublishActivity.this, "价格设置错误");
                }
                break;
            case R.id.item_map://选择详细地址
                if (!TextUtils.isEmpty(binding.itemTvRange.getContent())) {
                    //跳转详细地址界面
                    viewModel.getLocationLL(viewModel.addDeviceEntity.get().getLocation().getProvinceNo(),
                            viewModel.addDeviceEntity.get().getLocation().getCityNo(),
                            viewModel.addDeviceEntity.get().getLocation().getAreaNo());
                } else {
                    MToast.showToast(this, "请选择所在地区");
                }
                break;
            case R.id.item_tv_department_name://申请部门
                if (null != departmentData && departmentData.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this,
                            (options1, options2, options3, v) -> {
                                String content = departmentData.get(options1).getProjectscale();
                                binding.itemTvDepartmentName.setContent(content);
                                viewModel.addDeviceEntity.get().setDepartmentNo(departmentData.get(options1).getNo());
                                viewModel.addDeviceEntity.get().setDepartmentName(content);
                            }).build();
                    businessOption.setPicker(departmentData);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                } else {
                    MToast.showToast(DevicePublishActivity.this, "暂无申请部门");
                }
                break;
        }
    }

    public void setTimeList(List<PickSelectEntity<List<PickSelectEntity>>> timeUnitList) {
        this.timeUnitList = timeUnitList;
    }

    //设备属性
    public void setAttr(List<FilterEntity<List<FilterEntity>>> list) {
        attrList.clear();
        if (list != null) {
            attrList.addAll(list);
        }
        //attributesEntityList = binding.mAttrView.getChooseAttr();
        initAttrData(attrList, mEditAttrlist);
        //Intent intent = new Intent(DevicePublishActivity.this, PublicPublishAttributeActivity.class);
        //Bundle bundle = new Bundle();
        //bundle.putSerializable("list", (Serializable) list);
        //bundle.putSerializable("attributesEntityList", (Serializable) viewModel.addDeviceEntity.get().getDeviceAttrEntityList());
        //bundle.putInt("type", EVENT_PUBLISH_DEVICE_ATTR);
        //intent.putExtras(bundle);
        //startActivity(intent);
    }

    public void initAttrData(List<FilterEntity<List<FilterEntity>>> list, List<PublicAttrEntity> attributesEntityList) {
        binding.mAttrView.setData(list, attributesEntityList);
        binding.mAttrView.setAttrViewCallBack(new MachineAttrView.MachineAttrViewClickCallBack() {
            @Override
            public void hideSoft() {
                setSoftWareHide();
            }
        });
    }

    public void initDevicePublistAttrData() {
        if (!attrList.isEmpty()) {
            setAttr(attrList);
        } else {
            if (returnTypeEntity != null) {
                viewModel.getDeviceAttr(returnTypeEntity.getFirstNo(), returnTypeEntity.getSecondNo());
            } else if (addDeviceEntity != null && !TextUtils.isEmpty(addDeviceEntity.getFirstCategoryNo()) && !TextUtils.isEmpty(addDeviceEntity.getSecondCategoryNo())) {
                viewModel.getDeviceAttr(addDeviceEntity.getFirstCategoryNo(), addDeviceEntity.getSecondCategoryNo());
            }
        }
    }

    // 类型选择后的结果展示
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReturnEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == EVENT_PUBLISH_DEVICE_RETURN) {
            ReturnTypeEntity returnTypeEntityNow = (ReturnTypeEntity) event.getMessageData();
            if (returnTypeEntityNow.equals(returnTypeEntity)) {
                //如果选中的是之前的那个类型 什么都不做
            } else {
                returnTypeEntity = (ReturnTypeEntity) event.getMessageData();
                binding.itemTvType.setContent(returnTypeEntity.getFirstName() + "-" + returnTypeEntity.getSecondName());
                setDefaultTitle();

                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setFirstCategoryNo(returnTypeEntity.getFirstNo());
                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setFirstCategoryName(returnTypeEntity.getFirstName());
                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setSecondCategoryNo(returnTypeEntity.getSecondNo());
                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setSecondCategoryName(returnTypeEntity.getSecondName());
                attrList.clear();
                initDevicePublistAttrData();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttrEvent(PickEvent event) {
        if (event.getMessageTag() == EVENT_PUBLISH_DEVICE_ATTR) {
            Objects.requireNonNull(viewModel.addDeviceEntity.get()).setAttributeList((List<PublicAttrEntity>) event.getObject());
            //binding.itemTvAttribute.setContent("已选择");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (addDeviceEntity != null && addDeviceEntity.getLocation().getProvinceNo() != null
                    && addDeviceEntity.getLocation().getProvinceNo().equals(addressEntityList.get(x).getNo())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (addDeviceEntity != null) {
            if (addDeviceEntity.getLocation().getCityNo() != null)
                for (int x2 = 0; x2 < addressEntityList.get(cityPosition1).getChildren().size(); x2++) {
                    if (addDeviceEntity.getLocation().getCityNo().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getNo())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            if (addDeviceEntity.getLocation().getAreaNo() != null)
                for (int x3 = 0; x3 < addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().size(); x3++) {
                    if (addDeviceEntity.getLocation().getAreaNo().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getNo())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //税率
    public void showRate(List<PickSelectEntity> list) {
        tariffDatas = list;
    }

    //申请部门
    public void showDepartment(List<PickSelectEntity> list) {
        departmentData = list;
    }

    //客服
    public void getCustomerOrgDataS(List<ServiceEntity> serviceEntities) {
        this.serviceEntities = new ArrayList<PickSelectEntity>();
        for (int i = 0; i < serviceEntities.size(); i++) {
            PickSelectEntity pickSelectEntity = new PickSelectEntity();
            pickSelectEntity.setNo(serviceEntities.get(i).getId());
            pickSelectEntity.setProjectscale(serviceEntities.get(i).getName());
            this.serviceEntities.add(pickSelectEntity);
        }
        if (null != serviceEntities && serviceEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(DevicePublishActivity.this, (options1, options2, options3, v) -> {
                String content = this.serviceEntities.get(options1).getProjectscale();
                binding.itemTvServicer.setContent(content);
                Objects.requireNonNull(viewModel.addDeviceEntity.get()).setCustomerServiceId(this.serviceEntities.get(options1).getNo());
            }).build();
            businessOption.setPicker(this.serviceEntities);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }


    /**
     * 0.暂存:保存成功
     * 1.需要审批:提交成功(发布前提示需要审批对话框)
     * 2.不需要审批:发布成功(发布前提示不需要审批对话框)
     */
    public void showSuccess() {
        if ("0".equals(viewModel.addDeviceEntity.get().getStatus())) {
            MToast.showToast(this, "保存成功");
        } else if (isApprove) {
            MToast.showToast(this, "提交成功");
        } else {
            MToast.showToast(this, "发布成功");
        }
    }

    /**
     * 提示审批对话框
     *
     * @param b
     */
    public void showPublishTip(boolean b) {
        isApprove = b;
        String msg = b ? "确认提交当前审批业务？" : "当前内容不需要审核，提交后即发布，确认提交？";
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("系统提示")
                .setMsg(msg)
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        viewModel.addDeviceModel();
                        binding.btnSubmit.setClickable(false);
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }

    @Override
    public void onBackPressed() {
        if (!TextUtils.isEmpty(id)) {
            finish();
        } else {
            initDialog();
        }
    }

    public void initDialog() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("提示")
                .setMsg("你确定要返回上一步吗？返回后填写的数据将无法保存。")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        DevicePublishActivity.this.finish();
                    }

                    @Override
                    public void onLeftClick() {
                        return;
                    }
                }).show();
    }

    ;

    /**
     * 隐藏软键盘
     */
    private void setSoftWareHide() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
        }
    }

}

